﻿namespace Manhua2.Common
{
    using Manhua2.DataModel;
    using Manhua2.Helper;
    using System;
    using System.Threading.Tasks;
    using Windows.Networking.BackgroundTransfer;
    using Windows.Storage;

    public static class PageCacheManager
    {
        private static object _lockPoint = new object();

        public async static Task DownloadPageAsync(ComicPage page)
        {
            using (LockWrapper _wrapper = new LockWrapper(_lockPoint))
            {
                try
                {
                    string filename = string.Format("comic\\{0}\\{1}\\{2}", page.ComicId, page.ChapterId, page.Page);
                    string appx = string.Format("ms-appdata:///local/comic/{0}/{1}/{2}",
                                                page.ComicId, page.ChapterId, page.Page);
                    if (await MethodHelper.FileIsExists(filename))
                    {
                        page.Url = appx;
                        return;
                    }

                    var downloader = new BackgroundDownloader();
                    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                        filename,
                        CreationCollisionOption.ReplaceExisting);

                    var download = downloader.CreateDownload(new Uri(page.SourceUrl), file);
                    download.CostPolicy = BackgroundTransferCostPolicy.Always;
                    await HandleDownloadAsync(download, true);

                    page.Url = appx;
                }
                catch
                {
                }
            }
        }

        private async static Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            Progress<DownloadOperation> callback = new Progress<DownloadOperation>(DownloadProgress);

            if (start)
            {
                await download.StartAsync().AsTask(callback);
            }
            else
            {
                await download.AttachAsync().AsTask(callback);
            }
        }

        private static void DownloadProgress(DownloadOperation download)
        {
        }

    }
}
